package main

import (
	"ipgeo/geoapi"
	"log"
	"net/http"
	"os"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)

	e := echo.New()
	e.HideBanner = true
	e.Logger.SetLevel(2)
	e.Logger.SetPrefix("opi")
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())

	e.GET("/", index)
	e.File("/favicon.ico", "favicon.ico")

	e.GET("/geo", geoHandler)

	addr := ":80"
	if len(os.Args) >= 2 {
		addr = os.Args[1]
	}
	e.Logger.Fatal(e.Start(addr))
}

func geoHandler(ctx echo.Context) error {
	host := ctx.QueryParam("host")
	chid := ctx.QueryParam("chid")
	if host == "" {
		host = ctx.RealIP()
	}
	host, err := geoapi.CheckHost(host)
	if err != nil {
		ctx.Logger().Infof("checkhost:%+v", err)
		return ctx.JSON(http.StatusBadRequest, err)
	}
	ig, err := geoapi.GeoQuery(host, chid)
	if err != nil {
		ctx.Logger().Infof("geoquery:%+v", err)
		return ctx.JSON(http.StatusBadRequest, err)
	}
	return ctx.JSON(http.StatusOK, ig)
}

func index(ctx echo.Context) error {
	return ctx.JSON(http.StatusOK, echo.Map{
		"current": "/",
		"ipgeo":   "/geo?host={domain,ip}&chid={int}",
	})
}
